import express from 'express';
import Ret, { RetCode } from '../../bean/code/Ret';
const app = express();
import { excludeEmpty } from '../../utils';
import { db, Sequelize } from '../../dao/config';
import { converPage } from '../../bean/page';
import { Op } from 'Sequelize'
const User = require("../../dao/models/f_user")(db, Sequelize);
const Order = require("../../dao/models/f_order")(db, Sequelize);
const OrderProductRelation = require("../../dao/models/f_order_product_relation")(db, Sequelize);
const Product = require("../../dao/models/f_product")(db, Sequelize);
const ShippingAddress = require("../../dao/models/f_shipping_address")(db, Sequelize);


User.hasMany(Order, {
    foreignKey: "user_id"
})
Order.belongsTo(User, {
    foreignKey: "user_id",
    as: "user"
})
Order.belongsTo(ShippingAddress, {
    foreignKey: "shipment_id",
    as: "shipment"
})
Order.belongsToMany(Product, {
    foreignKey: "order_id",
    through: OrderProductRelation,
})

// Order.belongsTo(ShippingAddress,{
//     foreignKey:"shipment_id",
// })
Product.belongsToMany(Order, {
    foreignKey: "product_id",
    through: OrderProductRelation
})

/** 
 * 根据订单状态查询用户所有订单
 */
app.get("/order/getAllOrderByState", async (req, res) => {
    const { status, pageSize = 10, pageNum = 1, userId, isMention } = req.query;
    const where = { userId };
    if (+status > -1) {
        where.status = status;
    }
    if (+isMention > -1) {
        where.isMention = isMention;
    }
    const orders = await Order.findAndCount({
        where, include: [Product], order: [
            ['createTime', 'DESC'],
        ]
        , ...converPage(pageSize, pageNum)
    });
    res.json(Ret(RetCode.SUCCESS).setData(orders));
})
/** 
 * 根据后台筛选查询用户所有订单
 */
app.post("/order/getAllOrdersByCondition", async (req, res) => {
    let params = req.body, { page = {} } = params, { pageSize = 10, pageNum = 1 } = page;
    const condition = excludeEmpty(params, Order);
    if (Array.isArray(params.priceRange) && params.priceRange[0] && params.priceRange[1]) {
        condition.totalPrice = { [Op.between]: params.priceRange }
    }
    if (params.orderDateRange) {
        condition.createTime = { [Op.between]: params.orderDateRange }
    }

    const orders = await Order.findAndCount({
        where: condition,
        include: [
            { model: Product,through:{ attributes: ["count"],as:"relation" }},
            { model: User, as: "user", attributes: ["nickName"] },
            { model: ShippingAddress, as: "shipment" }
        ],
        order: [
            ['createTime', 'DESC'],
        ], ...converPage(pageSize, pageNum)
    });
    res.json(Ret(RetCode.SUCCESS).setData(orders));
})
/** 
 * 修改订单信息
 */
app.post("/order/updateOrder", async (req, res) => {
    let params = req.body, { id } = params;
    const condition = excludeEmpty(params, Order);
    const updateRes = await Order.update(condition, { where: { id } });
    res.json(Ret(RetCode.SUCCESS).setData(updateRes));
})


export default app;
